using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Sensor.UI.Utils;

/// <summary>
/// 高级性能监控器，提供详细的性能指标和数据完整性验证
/// </summary>
public class AdvancedPerformanceMonitor : IDisposable
{
    private readonly Timer _monitoringTimer;
    private readonly ConcurrentDictionary<string, PerformanceMetric> _metrics = new();
    private readonly ConcurrentQueue<DataIntegrityRecord> _integrityRecords = new();
    private readonly CancellationTokenSource _cancellationTokenSource = new();
    private bool _disposedValue = false;
    
    // 监控配置
    private readonly TimeSpan _monitoringInterval = TimeSpan.FromSeconds(1);
    private readonly int _maxIntegrityRecords = 1000;
    
    // 性能计数器
    private long _totalDataReceived = 0;
    private long _totalDataProcessed = 0;
    private long _totalDataDropped = 0;
    private long _totalProcessingTime = 0;
    private long _maxProcessingTime = 0;
    private long _minProcessingTime = long.MaxValue;
    
    public long TotalDataReceived => _totalDataReceived;
    public long TotalDataProcessed => _totalDataProcessed;
    public long TotalDataDropped => _totalDataDropped;
    public double AverageProcessingTime => _totalDataProcessed > 0 ? (double)_totalProcessingTime / _totalDataProcessed : 0;
    public long MaxProcessingTime => _maxProcessingTime;
    public long MinProcessingTime => _minProcessingTime == long.MaxValue ? 0 : _minProcessingTime;
    
    // 事件
    public event Action<PerformanceSnapshot>? OnPerformanceSnapshot;
    public event Action<IntegrityReport>? OnIntegrityReport;
    
    public AdvancedPerformanceMonitor()
    {
        // 设置监控定时器
        _monitoringTimer = new Timer(CollectMetrics, null, _monitoringInterval, _monitoringInterval);
        
        // 注册基本性能指标
        RegisterMetric("CPU使用率", "%");
        RegisterMetric("内存使用", "MB");
        RegisterMetric("GC内存", "MB");
        RegisterMetric("线程数", "个");
        RegisterMetric("句柄数", "个");
    }
    
    /// <summary>
    /// 注册性能指标
    /// </summary>
    /// <param name="name">指标名称</param>
    /// <param name="unit">单位</param>
    public void RegisterMetric(string name, string unit = "")
    {
        _metrics.TryAdd(name, new PerformanceMetric { Name = name, Unit = unit });
    }
    
    /// <summary>
    /// 更新指标值
    /// </summary>
    /// <param name="name">指标名称</param>
    /// <param name="value">指标值</param>
    public void UpdateMetric(string name, double value)
    {
        if (_metrics.TryGetValue(name, out var metric))
        {
            metric.UpdateValue(value);
        }
    }
    
    /// <summary>
    /// 记录数据处理
    /// </summary>
    /// <param name="sequenceNumber">序列号</param>
    /// <param name="processingTime">处理时间（毫秒）</param>
    /// <param name="dataSize">数据大小</param>
    public void RecordDataProcessing(long sequenceNumber, long processingTime, int dataSize)
    {
        Interlocked.Increment(ref _totalDataReceived);
        Interlocked.Increment(ref _totalDataProcessed);
        Interlocked.Add(ref _totalProcessingTime, processingTime);
        
        // 更新最大和最小处理时间
        InterlockedHelper.UpdateMax(ref _maxProcessingTime, processingTime);
        InterlockedHelper.UpdateMin(ref _minProcessingTime, processingTime);
        
        // 记录完整性信息
        var record = new DataIntegrityRecord
        {
            SequenceNumber = sequenceNumber,
            Timestamp = DateTime.UtcNow,
            ProcessingTime = processingTime,
            DataSize = dataSize
        };
        
        _integrityRecords.Enqueue(record);
        
        // 限制记录数量
        while (_integrityRecords.Count > _maxIntegrityRecords && _integrityRecords.TryDequeue(out _)) { }
    }
    
    /// <summary>
    /// 记录数据丢失
    /// </summary>
    /// <param name="sequenceNumber">序列号</param>
    /// <param name="reason">丢失原因</param>
    public void RecordDataLoss(long sequenceNumber, string reason)
    {
        Interlocked.Increment(ref _totalDataDropped);
        
        var record = new DataIntegrityRecord
        {
            SequenceNumber = sequenceNumber,
            Timestamp = DateTime.UtcNow,
            IsLost = true,
            LossReason = reason
        };
        
        _integrityRecords.Enqueue(record);
        
        // 限制记录数量
        while (_integrityRecords.Count > _maxIntegrityRecords && _integrityRecords.TryDequeue(out _)) { }
    }
    
    /// <summary>
    /// 收集系统指标
    /// </summary>
    private void CollectMetrics(object? state)
    {
        if (_disposedValue)
            return;
            
        try
        {
            // 收集系统性能指标
            using var process = Process.GetCurrentProcess();
            
            UpdateMetric("CPU使用率", GetCpuUsage(process));
            UpdateMetric("内存使用", process.WorkingSet64 / 1024.0 / 1024.0);
            UpdateMetric("GC内存", GC.GetTotalMemory(false) / 1024.0 / 1024.0);
            UpdateMetric("线程数", process.Threads.Count);
            UpdateMetric("句柄数", process.HandleCount);
            
            // 生成性能快照
            var snapshot = new PerformanceSnapshot
            {
                Timestamp = DateTime.UtcNow,
                TotalDataReceived = _totalDataReceived,
                TotalDataProcessed = _totalDataProcessed,
                TotalDataDropped = _totalDataDropped,
                AverageProcessingTime = AverageProcessingTime,
                MaxProcessingTime = _maxProcessingTime,
                MinProcessingTime = _minProcessingTime,
                Metrics = _metrics.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.GetCurrentValue())
            };
            
            OnPerformanceSnapshot?.Invoke(snapshot);
            
            // 生成完整性报告
            GenerateIntegrityReport();
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"性能监控错误: {ex.Message}");
        }
    }
    
    /// <summary>
    /// 获取CPU使用率
    /// </summary>
    private double GetCpuUsage(Process process)
    {
        try
        {
            process.Refresh();
            return process.TotalProcessorTime.TotalMilliseconds / Environment.ProcessorCount;
        }
        catch
        {
            return 0;
        }
    }
    
    /// <summary>
    /// 生成完整性报告
    /// </summary>
    private void GenerateIntegrityReport()
    {
        if (_integrityRecords.IsEmpty)
            return;
            
        var records = new List<DataIntegrityRecord>();
        while (records.Count < 100 && _integrityRecords.TryDequeue(out var record))
        {
            records.Add(record);
        }
        
        if (records.Count == 0)
            return;
            
        // 按序列号排序
        records.Sort((a, b) => a.SequenceNumber.CompareTo(b.SequenceNumber));
        
        // 检测序列号间隙
        var gaps = new List<SequenceGap>();
        long expectedSequence = records.FirstOrDefault()?.SequenceNumber ?? 0;
        
        foreach (var record in records)
        {
            if (record.SequenceNumber > expectedSequence)
            {
                gaps.Add(new SequenceGap
                {
                    StartSequence = expectedSequence,
                    EndSequence = record.SequenceNumber - 1,
                    Count = (int)(record.SequenceNumber - expectedSequence)
                });
            }
            expectedSequence = record.SequenceNumber + 1;
        }
        
        // 计算统计信息
        var lostRecords = records.Where(r => r.IsLost).ToList();
        var avgProcessingTime = records.Where(r => !r.IsLost).Average(r => r.ProcessingTime);
        var maxProcessingTime = records.Where(r => !r.IsLost).Max(r => r.ProcessingTime);
        
        var report = new IntegrityReport
        {
            Timestamp = DateTime.UtcNow,
            TotalRecords = records.Count,
            LostRecords = lostRecords.Count,
            SequenceGaps = gaps,
            AverageProcessingTime = avgProcessingTime,
            MaxProcessingTime = maxProcessingTime,
            LossRate = (double)lostRecords.Count / records.Count
        };
        
        OnIntegrityReport?.Invoke(report);
    }
    
    /// <summary>
    /// 获取当前性能快照
    /// </summary>
    public PerformanceSnapshot GetCurrentSnapshot()
    {
        return new PerformanceSnapshot
        {
            Timestamp = DateTime.UtcNow,
            TotalDataReceived = _totalDataReceived,
            TotalDataProcessed = _totalDataProcessed,
            TotalDataDropped = _totalDataDropped,
            AverageProcessingTime = AverageProcessingTime,
            MaxProcessingTime = _maxProcessingTime,
            MinProcessingTime = _minProcessingTime,
            Metrics = _metrics.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.GetCurrentValue())
        };
    }
    
    /// <summary>
    /// 重置所有计数器
    /// </summary>
    public void ResetCounters()
    {
        Interlocked.Exchange(ref _totalDataReceived, 0);
        Interlocked.Exchange(ref _totalDataProcessed, 0);
        Interlocked.Exchange(ref _totalDataDropped, 0);
        Interlocked.Exchange(ref _totalProcessingTime, 0);
        Interlocked.Exchange(ref _maxProcessingTime, 0);
        Interlocked.Exchange(ref _minProcessingTime, long.MaxValue);
        
        // 清空完整性记录
        while (_integrityRecords.TryDequeue(out _)) { }
    }
    
    #region IDisposable实现
    protected virtual void Dispose(bool disposing)
    {
        if (!_disposedValue)
        {
            if (disposing)
            {
                _cancellationTokenSource.Cancel();
                _monitoringTimer?.Dispose();
            }
            _disposedValue = true;
        }
    }
    
    public void Dispose()
    {
        Dispose(disposing: true);
        GC.SuppressFinalize(this);
    }
    #endregion
}

/// <summary>
/// 性能指标
/// </summary>
public class PerformanceMetric
{
    private double _currentValue;
    private double _minValue = double.MaxValue;
    private double _maxValue = double.MinValue;
    private double _totalValue;
    private long _updateCount;
    
    public string Name { get; set; } = string.Empty;
    public string Unit { get; set; } = string.Empty;
    
    public double CurrentValue => _currentValue;
    public double MinValue => _minValue == double.MaxValue ? 0 : _minValue;
    public double MaxValue => _maxValue == double.MinValue ? 0 : _maxValue;
    public double AverageValue => _updateCount > 0 ? _totalValue / _updateCount : 0;
    
    public void UpdateValue(double value)
    {
        _currentValue = value;
        _totalValue += value;
        _updateCount++;
        
        if (value < _minValue) _minValue = value;
        if (value > _maxValue) _maxValue = value;
    }
    
    public double GetCurrentValue() => _currentValue;
}

/// <summary>
/// 性能快照
/// </summary>
public class PerformanceSnapshot
{
    public DateTime Timestamp { get; set; }
    public long TotalDataReceived { get; set; }
    public long TotalDataProcessed { get; set; }
    public long TotalDataDropped { get; set; }
    public double AverageProcessingTime { get; set; }
    public long MaxProcessingTime { get; set; }
    public long MinProcessingTime { get; set; }
    public Dictionary<string, double> Metrics { get; set; } = new();
    
    public override string ToString()
    {
        return $"时间: {Timestamp:HH:mm:ss}, " +
               $"接收: {TotalDataReceived}, 处理: {TotalDataProcessed}, 丢弃: {TotalDataDropped}, " +
               $"平均处理时间: {AverageProcessingTime:F2}ms, " +
               $"最大处理时间: {MaxProcessingTime}ms, " +
               $"最小处理时间: {MinProcessingTime}ms";
    }
}

/// <summary>
/// 数据完整性记录
/// </summary>
public class DataIntegrityRecord
{
    public long SequenceNumber { get; set; }
    public DateTime Timestamp { get; set; }
    public long ProcessingTime { get; set; }
    public int DataSize { get; set; }
    public bool IsLost { get; set; }
    public string LossReason { get; set; } = string.Empty;
}

/// <summary>
/// 序列号间隙
/// </summary>
public class SequenceGap
{
    public long StartSequence { get; set; }
    public long EndSequence { get; set; }
    public int Count { get; set; }
    
    public override string ToString()
    {
        return $"序列号 {StartSequence}-{EndSequence} (共{Count}个)";
    }
}

/// <summary>
/// 完整性报告
/// </summary>
public class IntegrityReport
{
    public DateTime Timestamp { get; set; }
    public int TotalRecords { get; set; }
    public int LostRecords { get; set; }
    public List<SequenceGap> SequenceGaps { get; set; } = new();
    public double AverageProcessingTime { get; set; }
    public long MaxProcessingTime { get; set; }
    public double LossRate { get; set; }
    
    public override string ToString()
    {
        return $"时间: {Timestamp:HH:mm:ss}, " +
               $"总记录: {TotalRecords}, 丢失: {LostRecords}, " +
               $"丢失率: {LossRate:P2}, " +
               $"平均处理时间: {AverageProcessingTime:F2}ms, " +
               $"最大处理时间: {MaxProcessingTime}ms";
    }
}

/// <summary>
/// 原子操作辅助类
/// </summary>
internal static class InterlockedHelper
{
    public static void UpdateMax(ref long location, long value)
    {
        long current, initial;
        do
        {
            initial = location;
            current = Math.Max(initial, value);
        } while (initial != current && Interlocked.CompareExchange(ref location, current, initial) != initial);
    }
    
    public static void UpdateMin(ref long location, long value)
    {
        long current, initial;
        do
        {
            initial = location;
            current = Math.Min(initial, value);
        } while (initial != current && Interlocked.CompareExchange(ref location, current, initial) != initial);
    }
}